package com.liao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liao.dto.BookDTO;
import com.liao.entity.Book;
import com.liao.entity.BookCategory;
import com.liao.mapper.BookMapper;
import com.liao.service.BookCategoryService;
import com.liao.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 图书服务实现类
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Resource
    private BookCategoryService bookCategoryService;

    /**
     * 分页查询图书列表
     *
     * @param page       分页参数
     * @param name       图书名称（可选）
     * @param author     作者（可选）
     * @param categoryId 分类ID（可选）
     * @return 分页图书列表
     */
    @Override
    public Page<Book> getBookPage(Page<Book> page, String name, String author, Long categoryId) {
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        queryWrapper.like(StringUtils.hasText(name), Book::getName, name)
                .like(StringUtils.hasText(author), Book::getAuthor, author)
                .eq(categoryId != null, Book::getCategoryId, categoryId);
        
        // 查询并返回结果
        return this.page(page, queryWrapper);
    }

    /**
     * 添加图书
     *
     * @param bookDTO 图书信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addBook(BookDTO bookDTO) {
        // 检查分类是否存在
        if (bookDTO.getCategoryId() != null) {
            BookCategory category = bookCategoryService.getById(bookDTO.getCategoryId());
            if (category == null) {
                throw new RuntimeException("图书分类不存在");
            }
        }
        
        // 检查ISBN是否已存在
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Book::getIsbn, bookDTO.getIsbn());
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("ISBN编号已存在");
        }
        
        // 创建图书对象并保存
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        
        return this.save(book);
    }

    /**
     * 修改图书
     *
     * @param bookDTO 图书信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBook(BookDTO bookDTO) {
        // 检查图书是否存在
        Book existBook = this.getById(bookDTO.getId());
        if (existBook == null) {
            throw new RuntimeException("图书不存在");
        }
        
        // 检查分类是否存在
        if (bookDTO.getCategoryId() != null) {
            BookCategory category = bookCategoryService.getById(bookDTO.getCategoryId());
            if (category == null) {
                throw new RuntimeException("图书分类不存在");
            }
        }
        
        // 检查ISBN是否已存在（排除自身）
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Book::getIsbn, bookDTO.getIsbn())
                .ne(Book::getId, bookDTO.getId());
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("ISBN编号已存在");
        }
        
        // 更新图书信息
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        book.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(book);
    }

    /**
     * 删除图书
     *
     * @param id 图书ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBook(Long id) {
        // 检查图书是否存在
        Book book = this.getById(id);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        
        // 删除图书（逻辑删除）
        return this.removeById(id);
    }

    /**
     * 根据ID获取图书详情
     *
     * @param id 图书ID
     * @return 图书详情
     */
    @Override
    public Book getBookById(Long id) {
        return this.getById(id);
    }
    
    /**
     * 根据ID获取图书详情
     *
     * @param id 图书ID
     * @return 图书详情
     */
    @Override
    public Book getBookDetail(Long id) {
        return this.getById(id);
    }

    /**
     * 更新图书库存
     *
     * @param id    图书ID
     * @param stock 库存数量
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBookStock(Long id, Integer stock) {
        // 检查图书是否存在
        Book book = this.getById(id);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        
        // 更新库存
        book.setStock(stock);
        book.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(book);
    }
    
    /**
     * 更新图书库存
     *
     * @param id    图书ID
     * @param stock 库存变化量（正数增加，负数减少）
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStock(Long id, Integer stock) {
        // 检查图书是否存在
        Book book = this.getById(id);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        
        // 计算新库存
        int newStock = book.getStock() + stock;
        if (newStock < 0) {
            throw new RuntimeException("库存不足");
        }
        
        // 更新库存
        book.setStock(newStock);
        book.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(book);
    }
}